# -*- coding: utf-8 -*-
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import Brand
from meiduo_admin.serializers.brand import BrandSerializer
from meiduo_admin.utils import PageNum


class BrandViewSet(ModelViewSet):
    serializer_class = BrandSerializer
    pagination_class = PageNum
    queryset = Brand.objects.all()

    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        logo = request.data.get('logo')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(logo.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id'].replace('\\', '/')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')

        # 保存品牌
        brand = Brand.objects.create(name=name, first_letter=first_letter, logo=image_url)

        return Response({
            'name': brand.name,
            'first_letter': brand.first_letter,
            'logo': image_url
        }, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            brand = Brand.objects.get(id=pk)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取前端传递的image文件
        logo = request.data.get('logo')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(logo.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id'].replace('\\', '/')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        # 删除之前的图片
        client.delete_file(brand.logo.name)

        # 保存品牌
        brand.name = name
        brand.first_letter = first_letter
        brand.logo = image_url
        brand.save()

        return Response({
            'name': brand.name,
            'first_letter': brand.first_letter,
            'logo': image_url
        }, status=status.HTTP_200_OK)
